/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servletUpload;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import sessionbean.AssignmentFacadeLocal;
import sessionbean.StaffProfileFacadeLocal;
import sessionbean.SubjectFacadeLocal;
import supportlearning.entities.Assignment;
import supportlearning.entities.StaffProfile;
import supportlearning.entities.Subject;

/**
 *
 * @author VoVanHai
 */
public class servletupload extends HttpServlet {

    @EJB
    private SubjectFacadeLocal subjectFacade;
    @EJB
    private StaffProfileFacadeLocal staffProfileFacade;
    @EJB
    private AssignmentFacadeLocal assignmentFacade;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String startdate = null;
        String enddate = null;
        try {

            String itemName = "";
            int size;
            String sess = (String) session.getAttribute("sessuser");
            //to get the content type information from JSP Request Header
            String contentType = request.getContentType();
            //here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (!isMultipart) {
                out.println("not a multipart");
            } else {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = null;
                try {
                    items = upload.parseRequest(request);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Iterator itr = items.iterator();
                while (itr.hasNext()) {
                    FileItem item = (FileItem) itr.next();
                    if (item.isFormField()) {
                        String name = item.getFieldName();
                        String value = item.getString();
                        if (name.equals("txtstart")) {
                            startdate = value;
                        }
                        if (name.equals("txtend")) {
                            enddate = value;
                        }
                    } else {
                        try {
                            itemName = item.getName();
                            size = (int) item.getSize();
                            System.out.println(size);
                            File ff = new File(itemName);
                            itemName =System.currentTimeMillis()+ff.getName();
                            String saveFile = getServletContext().getRealPath("");
                            saveFile = saveFile.substring(0, saveFile.lastIndexOf("\\default") + 8);
                            saveFile += "/deploy/staff.war/" + itemName;
                            System.err.println("___________" + saveFile);
                            File savedFile = new File(saveFile);
                            item.write(savedFile);

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
                System.out.println(startdate);
                System.out.println(enddate);
                Assignment asm = new Assignment();
                asm.setAsmName(itemName);
                asm.setAsmFile("http://localhost:8080/staff/"+ itemName);
                Date d1 = new Date(startdate);
                Date d2 = new Date(enddate);
                asm.setStartDate(d1);
                asm.setEndDate(d2);
                StaffProfile staffid = staffProfileFacade.findStaffByID(sess);
                asm.setStaffProfile(staffid);
                int id = Integer.parseInt(request.getParameter("id"));
                Subject subid = subjectFacade.findSubByID(id);
                asm.setSubject(subid);
                assignmentFacade.create(asm);
                response.sendRedirect("ServletSub");
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);




    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);




    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";


    }// </editor-fold>
}
